import { defineStore } from 'pinia'
import { getDepartmentList, getDepartmentTree, createDepartment, updateDepartment, deleteDepartment } from '@/api/department'

export const useDepartmentStore = defineStore('department', {
  state: () => ({
    departmentList: [],
    departmentTree: [],
    loading: false
  }),

  actions: {
    async fetchDepartmentList(params) {
      this.loading = true
      try {
        const response = await getDepartmentList(params)
        this.departmentList = response.data || []
        return response.data
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    async fetchDepartmentTree() {
      try {
        const response = await getDepartmentTree()
        this.departmentTree = response.data || []
        return response.data
      } catch (error) {
        throw error
      }
    },

    async createDepartment(data) {
      try {
        return await createDepartment(data)
      } catch (error) {
        throw error
      }
    },

    async updateDepartment(id, data) {
      try {
        return await updateDepartment(id, data)
      } catch (error) {
        throw error
      }
    },

    async deleteDepartment(id) {
      try {
        return await deleteDepartment(id)
      } catch (error) {
        throw error
      }
    }
  }
})